<template>
    <div @touchstart="startAccumulate" @mouseenter="startAccumulate" @mouseleave="stopAccumulate" class="relative">
        <header class="header">
            <div class="container">
                <h1>{{detail.title}}</h1>
                <p>{{detail.description}}</p>
                <button @click="showSkillCourse" class="btn btn-outline btn-white mt-2" v-if="skill">查看本课程所在技能</button>
            </div>
        </header>
        <div class="modal mt-8" :class="{block:show_skill_course}" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">技能课程</h5>
                        <button type="button" class="close" @click="show_skill_course=false" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body" @click="show_skill_course=false">
                        <course-tree-view :courses="skillDetail.courses" :career="career"
                                          :skill="skill"></course-tree-view>
                    </div>
                </div>
            </div>
        </div>
        <main class="container" ref="page">
            <div class="full-ribbon-bar mt-6"></div>
            <article class="max-w-2xl mx-auto py-6">
                <course-content :content="detail.content" :type="detail.content_type"></course-content>
            </article>
            <div class="full-ribbon-bar mb-4"></div>
            <div>完成本课程将获得 {{detail.exp}} 经验值 {{detail.depth}} 深度值</div>
            <work-list :works="works" @complete="completeWork"></work-list>
            <div class="button-wrap primary" v-if="!detail.is_completed">
                <button class="button" @click="complete">完成</button>
            </div>
            <div v-else>您已完成过本课程</div>
            <div v-show="next_courses.length">
                <h3 class="text-2xl mb-4"><span class="border-b border-purple">
                    下节课程
                </span></h3>
                <template v-for="course in next_courses">
                    <course-tree-node :course="course" :key="course.id" :career="career"
                                      :skill="skill"></course-tree-node>
                </template>
            </div>
        </main>

        <!--<template v-if="detail.user_course.completed_at">-->
        <!--<div class="submit-wrap selected">-->
        <!--<button class="submit">已完成</button>-->
        <!--</div>-->
        <!--</template>-->
        <!--<template v-else>-->

        <!--</template>-->

        <learn-counter :learn-count="learn_count"></learn-counter>
    </div>
</template>

<script>
    import CourseContent from "../components/CourseContent";
    import WorkList from "../components/WorkList";
    import LearnCounter from "../components/LearnCounter";
    import CourseTreeNode from '../components/CourseTreeNode'
    import CourseTreeView from '../components/CourseTreeView'

    export default {
        components: {CourseContent, WorkList, LearnCounter, CourseTreeNode, CourseTreeView},
        data() {
            return {
                detail: {},
                interval: null,
                next_courses: [],
                works: [],
                learn_count: 0,
                show_skill_course: false,
                skillDetail: {},
            }
        },
        computed: {
            career() {
                return this.$route.query.career;
            }, skill() {
                return this.$route.query.skill;
            }
        },

        watch: {
            '$route'(to, from) {
                this.getCourse();
                this.getWorks();
                this.next_courses = [];

            }
        },
        methods: {
            accumulate() {
                if (this.$route.name === 'course') {
                    axios.post('courses/' + this.$route.params.course + '/accumulate', {}).then((res) => {
                        this.learn_count = parseInt(res.data);
                    })
                } else {
                    this.stopAccumulate();
                }

            },
            getCourse() {
                axios.get('courses/' + this.$route.params.course, {
                    params: {
                        career: this.$route.query.career,
                        skill: this.$route.query.skill
                    }
                }).then((res) => {
                    this.detail = res.data.data;
                    if (this.detail.is_completed) {
                        this._findNextCourse();
                    }
                })
            }, getWorks() {
                axios.get('courses/' + this.$route.params.course + '/works').then((res) => {
                    this.works = res.data.data;
                })
            }, _submitWork() {
                let workPromise = work_result => axios.post('/works/' + work_result.id, {result: work_result.result}).then(res => console.log(res));
                let workPromises = _.map(this.work_results, workPromise);

                axios.all(workPromises).then(res => {
                    console.log(res);
                    this.$toasted.success('提交作业成功');
                    this.getWorks();
                })
            }, _completeCourse() {
                axios.post('courses/' + this.$route.params.course + '/complete?skill=' + this.$route.query.skill
                ).then(res => {
                    this.$toasted.success('成功完成本课程' + (this.detail.exp > 0 ? '，经验值+' + this.detail.exp : ''));
                });
            }, _findNextCourse() {
                if (this.skill) {
                    axios.get('skills/' + this.skill + '/courses/' + this.$route.params.course + '/next').then((res) => {
                        this.next_courses = res.data.data;
                        if (this.next_courses.length === 0) {
                            this.showSkillCourse();
                        }
                    })
                }
            }, complete() {
                console.log(this.works);

                if (this.works.length && !this.works[0].user_result) {
                    this._submitWork();
                }

                this._completeCourse();
                this._findNextCourse();

            }, completeWork(result) {
                this.work_results = result;
            }, startAccumulate() {
                if (!this.interval) {
                    this.interval = setInterval(() => {
                        this.accumulate()
                    }, 3000)
                }
            }, stopAccumulate() {
                clearInterval(this.interval);
                this.interval = null;
            }, showSkillCourse() {
                if (this.skillDetail) {
                    this.getSkill();
                }
                this.show_skill_course = true;
            }, getSkill() {
                axios.get('skills/' + this.$route.query.skill, {params: {career: this.$route.query.career}}).then((res) => {
                    this.skillDetail = res.data.data;
                })
            }
        }, created() {
            // let that = this;
            this.getCourse();
            this.getWorks();
            this.accumulate();

            /*
            let hiddenProperty = 'hidden' in document ? 'hidden' :
                'webkitHidden' in document ? 'webkitHidden' :
                    'mozHidden' in document ? 'mozHidden' :
                        null;
            var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
            var onVisibilityChange = function () {
                if (document[hiddenProperty]) {
                    clearInterval(that.interval);
                }
            };
            // document.addEventListener(visibilityChangeEvent, onVisibilityChange);
            this.$refs.page.onmouseout = function () {
                clearInterval(that.interval);
            };
            // that.accumulate();
            this.$refs.page.onmouseover = function () {
                // clearInterval(that.interval);
                if (!that.interval) {
                    that.interval = setInterval(() => {
                        that.accumulate()
                    }, 3000)
                }

            }
            */
        }
    }
</script>

<style scoped>

</style>